<?php

namespace App\Http\Controllers\Admin\ContentManager;

use App\Enums\BannerEnum;
use App\Enums\MyPageBannerEnum;
use App\Exceptions\BasicException;
use phpDocumentor\Reflection\Type;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

//引用http请求类
use App\Response\Response;

class AdController extends BaseController
{

    /**
     * @api {post} /content-manager/list-ad 轮播图创建
     * @apiVersion 0.1.0
     * @apiName 内容管理-轮播图创建
     * @apiGroup 内容管理
     * @apiParam {number} item_id                       房间id 可选
     * @apiParam {string} link_url                      链接地址 可选
     * @apiParam {number} display                       状态 0：不显示 1：显示 必传
     * @apiParam {number} sort                          排序 必传
     * @apiParam {number} type                          轮播图类型 类型 1房间2文章3链接4详情图5H5页面6无操作 必传
     * @apiParam {string} title                         轮播图名称 必传
     * @apiParam {string} content                       轮播图图片 必传
     * @apiParam {string} detail_pictures               详情图片  可选
     * @apiParam {int} category_id              banner分类id0为无，必传
     * @apiParam {int} skip_target              跳转位置id（category_id==4 必填）
     * @apiParam {int} start_time              开始时间，必传
     * @apiParam {int} end_time              结束时间，必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function create(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'item_id'         => 'filled|numeric',
            'link_url'        => 'filled|string|active_url',
            'display'         => 'required|numeric|in:0,1',
            'sort'            => 'required|numeric|min:1|max:2100000000',
            'type'            => 'required|numeric|in:1,2,3,4,5,6',
            'title'           => 'required|string|max:255',
            'content'         => 'required|string',
            'detail_pictures' => 'filled|string|active_url',
            'category_id'     => 'required|integer|min:-1',
            'skip_target'     => 'integer|min:-1',
            'start_time'     => 'required|integer',
            'end_time'     => 'required|integer',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $params = $request->only('item_id', 'link_url', 'display', 'sort', 'type', 'title', 'content', 'detail_pictures', 'category_id', 'skip_target', 'start_time', 'end_time');

        if ($params['category_id'] == -1) {
            $params['category_id'] = 0;
        }
        if ($params['display'] == 0) {
            $params['category_id'] = 0;
        }
        $categoryId = $params['category_id'];

        if ($params['type'] == 1) {
            if (empty($params['item_id'])) {
                throw new BasicException(10001, "房间id不能为空！");
            }

            $roomRes = app("model_user_room")->where("room_id", $params['item_id'])->first();
            if (empty($roomRes)) {
                throw new BasicException(10001, "不是合法的房间id！");
            }
            $params['item_id'] = $roomRes->id;
        }

        if ($params['type'] == 3) {
            if (empty($params['link_url'])) {
                throw new BasicException(10001, "跳转链接不能为空！");
            }
        }

        $bannerCategory = app('model_banner_category')
            ->select('id')
            ->where('id', $categoryId)->where('status', 1)->first();
        if (empty($bannerCategory)&&$categoryId!==0) {
            throw new BasicException(0, '分类id错误');
        }
        if ($categoryId == BannerEnum::BANNER_MY||$categoryId == BannerEnum::BANNER_PLAY) {
            $this->setMyBannerCheckData($params, $categoryId);
        }
        /*额外展示位每个位置仅可存在1个banner,否则原先banner类型改为无*/
        $this->setIndexBannerCheckData($params,$categoryId);


        $res = app('repo_content');

        $rows = $res->addAd($params);
        if (!$rows) {
            throw new BasicException(10001, "插入失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /content-manager/list-ad 轮播图删除
     * @apiVersion 0.1.0
     * @apiName 内容管理-轮播图删除
     * @apiGroup 内容管理
     * @apiParam {string} ids                       字符串分割的id 必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function del(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $idsStr = $request->input("ids");
        $idsArr = explode(",", $idsStr);
        $rows = app('repo_content')->delAd($idsArr);

        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {put} /content-manager/list-ad 轮播图修改
     * @apiVersion 0.1.0
     * @apiName 内容管理-轮播图修改
     * @apiGroup 内容管理
     * @apiParam {number} id
     * @apiParam {number} item_id                       房间id 可选
     * @apiParam {string} link_url                      链接地址 可选
     * @apiParam {number} display                       状态 0：不显示 1：显示 必传
     * @apiParam {number} sort                          排序 必传
     * @apiParam {number} type                          轮播图类型 类型 1房间2文章3链接4详情图5H5页面6无操作 必传
     * @apiParam {string} title                         轮播图名称 必传
     * @apiParam {string} content                       轮播图图片 必传
     * @apiParam {string} detail_pictures               详情图片  可选
     * @apiParam {int} category_id              banner分类id0为无，必传
     * @apiParam {int} skip_target              跳转位置id（category_id==4 必填）
     * @apiParam {int} start_time              开始时间，必传
     * @apiParam {int} end_time              结束时间，必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function update(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->input(), [
            'id'         => 'required|integer',
            'item_id'         => 'filled|numeric',
            'link_url'        => 'filled|string|active_url',
            'display'         => 'required|numeric|in:0,1',
            'sort'            => 'required|numeric|min:1|max:2100000000',
            'type'            => 'required|numeric|in:1,2,3,4,5,6,7,8',
            'title'           => 'required|string|max:255',
            'content'         => 'required|string',
            'detail_pictures' => 'filled|string|active_url',
            'category_id'     => 'required|integer|min:-1',
            'skip_target'     => 'integer|min:-1',
            'start_time'     => 'required|integer',
            'end_time'     => 'required|integer'
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $params = $request->only('id', 'item_id', 'link_url', 'display', 'sort', 'type', 'title', 'content', 'detail_pictures', 'category_id', 'skip_target', 'start_time', 'end_time');

        $id = $params['id'];
        if ($params['category_id'] == -1) {
            $params['category_id'] = 0;
        }
        if ($params['display'] == 0) {
            $params['category_id'] = 0;
        }
        $categoryId = $params['category_id'];


        if ($params['type'] == 1) {
            if (empty($params['item_id'])) {
                throw new BasicException(10001, "房间id不能为空！");
            }

            $roomRes = app("model_user_room")->where("room_id", $params['item_id'])->first();
            if (empty($roomRes)) {
                throw new BasicException(10001, "不是合法的房间id！");
            }
            $params['item_id'] = $roomRes->id;
        }

        if ($params['type'] == 3) {
            if (empty($params['link_url'])) {
                throw new BasicException(10001, "跳转链接不能为空！");
            }
        }
        if ($params['type'] == 6) {
            $params['link_url'] = '';
        }
        if ($categoryId == BannerEnum::BANNER_MY||$categoryId == BannerEnum::BANNER_PLAY||$categoryId == BannerEnum::BANNER_WELFARE_CENTER) {

            $this->setMyBannerCheckData($params,$categoryId, $id);
        }
        /*额外展示位每个位置仅可存在1个banner,否则原先banner类型改为无*/
        $this->setIndexBannerCheckData($params,$categoryId, $id);


        $bannerCategory = app('model_banner_category')
            ->select('id')
            ->where('id', $categoryId)->where('status', 1)->first();
        if (empty($bannerCategory)&&$categoryId!==0) {
            throw new BasicException(0, '分类id错误');
        }

        $res = app('repo_content');

        $rows = $res->saveAd(["id" => $id], $params);
        if (!$rows) {
            throw new BasicException(10001, "更新失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /content-manager/list-ad 轮播图列表
     * @apiVersion 0.1.0
     * @apiName 内容管理-轮播图列表
     * @apiGroup 内容管理
     * @apiParam {number} display 状态 0：不显示 1：显示 可选
     * @apiParam {number} keyword 轮播图名称 可选
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id": 57,
     * "category_id": 1,
     * "title(名称)": "万圣节排名",
     * "type(类型 1房间2文章3链接4详情图5H5页面6无操作)": 0,
     * "item_id(房间id)": 0,
     * "link_url(展示url)": "",
     * "description 描述": null,
     * "start_time 显示开始时间": '1970-01-01 08:00:01',
     * "end_time 显示结束时间": '1970-01-01 08:00:01',
     * "display(状态 0：不显示 1：显示)": 1,
     * "category_name(额外展示位)": "无",
     * "content(图片)": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5fa373f0c7baa.png",
     * "sort(排序)": 1,
     * "detail_pictures(详细图片)": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5fa373eb4c601.png",
     * "add_time": "1970-01-01 08:00:00"
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 10,
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     */
    public function list(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'keyword' => 'filled|string',
            'display' => 'filled|numeric|in:0,1',
            'perPage' => 'filled|numeric',
            'page'    => 'filled|numeric',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $list = app('repo_content')->getAdQueryList($request->input());

        return Response::sendList($list);
    }

    /**
     * @api {get} /content-manager/list-ad-category 轮播图类别列表
     * @apiVersion 0.1.0
     * @apiName 内容管理-轮播图类别列表
     * @apiGroup 内容管理
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": [
     * {
     * "id": 1,
     * "title": "首页轮播图",
     * "add_time": 0,
     * "is_have(是否已存在 1是 0否)": 0,
     * "status": 1
     * }
     * ]
     * }
     */
    public function bannerCategoryList()
    {
        $list = app('model_banner_category')->where('status', 1)->get();
        foreach ($list as $item) {
            $bannerRes = app('model_banner')
                ->select('id','title')
                ->where('category_id', $item->id)->first();
            $item->is_have = $bannerRes ? 1 : 0;
            $item->is_have_name = $bannerRes->title ??'';
        }

        return Response::sendData($list);
    }


    /**
     * @api {get} /content-manager/list-ad/banner-skip 获取我的界面banner跳转类型
     * @apiVersion 0.1.0
     * @apiName 获取我的界面banner跳转类型
     * @apiGroup 内容管理
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": [
     * {
     * "tagged": "举报用户界面",
     * "val": 31
     * },
     * {
     * "tagged": "举报房间界面",
     * "val": 32
     * },
     * {
     * "tagged": "我的背包界面",
     * "val": 33
     * }
     * ]
     * }
     */
    public function getMyBannerSkipType()
    {
        $skiparr = MyPageBannerEnum::getConst();
        $skiparr = array_values($skiparr);

        return Response::sendData($skiparr);
    }

    //配置操作检验数据
    private function setMyBannerCheckData($params, $categoryId, $id = 0)
    {
        $skiparr = MyPageBannerEnum::getConst();

        $skiparr = array_values($skiparr);

        $skiparrTarget = array_column($skiparr, 'val');
        if (!isset($params['skip_target'])) {
            throw new BasicException(10001, "请选择跳转类型");
        }
        if ($id == 0) {                                                                //添加
            if ( !in_array($params['skip_target'], $skiparrTarget)) {
                throw new BasicException(10001, "跳转类型错误");
            }

        } else {//修改

            if ( !in_array($params['skip_target'], $skiparrTarget)) {
                throw new BasicException(10001, "跳转类型错误");
            }
        }

        return true;
    }

    //额外展示位每个位置仅可存在1个banner,否则原先banner类型改为无
    private function setIndexBannerCheckData($params, $categoryId, $id = 0)
    {
        if ($id == 0) {                                                                //添加
            $bannerHave = app('model_banner')->where(['category_id' => $categoryId])->first();
            if ($bannerHave) {
                app('model_banner')->where(['category_id' => $categoryId])->update([
                    'category_id' => 0,
                ]);
            }
        } else {//修改

            $bannerHave = app('model_banner')->where('id', $id)->first();
            if (empty($bannerHave)) {
                throw new BasicException(10001, "id错误");
            }
            $bannerHave = app('model_banner')->where([['id', '!=', $id], 'category_id' => $categoryId])->first();
            if ($bannerHave) {
                app('model_banner')->where([['id', '!=', $id], 'category_id' => $categoryId])->update([
                    'category_id' => 0,
                ]);
            }
        }

        return true;
    }
}
